﻿using huaxin_core;
using huaxin_Impl;
using huaxin_Interface;
using Senparc.Weixin.MP.TenPayLibV3;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace huaxin_luckdraw.Controllers
{
    /// <summary>
    /// 微信支付域名回调
    /// </summary>
    public class NotifyPayController : Controller
    {

        // GET: NotifyPay
        public ActionResult PayNotifyUrl()
        {

            LogHelper.WriteInfo("订单开始处理");


            ResponseHandler payNotifyRepHandler = new ResponseHandler(null);
            payNotifyRepHandler.SetKey("huaxin_719");
            try
            {

                //返回的参数
                string return_code = payNotifyRepHandler.GetParameter("return_code");//返回状态码
                string return_msg = payNotifyRepHandler.GetParameter("return_msg");//返回信息
                string result_code= payNotifyRepHandler.GetParameter("result_code");

                //因为微信服务器会多次推送通知到这里，所以需要在这里判断订单是否已经完成支付，
                //如果完成，则不进行下面操作
                string out_trade_no = payNotifyRepHandler.GetParameter("out_trade_no");//商户订单号
                //验证请求是否从微信发过来（安全）
                if (return_code.ToUpper() == "SUCCESS"&& result_code.ToUpper() == "SUCCESS")
                {

                    //微信支付订单号
                    string transaction_id = payNotifyRepHandler.GetParameter("transaction_id");
                    //正确的订单处理
                    LogHelper.WriteInfo("订单号:"+ out_trade_no+"|微信支付订单号:"+ transaction_id);
                    huaxin_IPayOrder _payOrder = new huaxin_PayOrderImpl();
                    int result = _payOrder.OrderNotifyPay(out_trade_no,transaction_id);
                    if (result > 0)
                    {
                        payNotifyRepHandler.SetParameter("return_msg", "OK");
                        payNotifyRepHandler.SetParameter("return_code", "SUCCESS");
                    }
                    else
                    {
                        payNotifyRepHandler.SetParameter("return_code", "FAIL");
                        payNotifyRepHandler.SetParameter("return_msg", "交易失败");
                    }
                }
                else
                {
                    LogHelper.WriteInfo("订单签名失败:"+ out_trade_no);
                    //错误的订单处理
                    payNotifyRepHandler.SetParameter("return_code", "FAIL");
                    payNotifyRepHandler.SetParameter("return_msg", "交易失败");
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteError("异常处理",ex);
            }

            return Content(payNotifyRepHandler.ParseXML());
        }

    }
}